#include "math.h"
#include "GL/GLU.h"

Vec3 pickingRay( const QPointF& mousePos, Vec3* pStart, Vec3* pEnd)
{
	double matModelView[16], matProjection[16]; 
	int viewport[4]; 
	
	double startX, startY, startZ;
	double endX, endY, endZ;

	glGetDoublev( GL_MODELVIEW_MATRIX, matModelView ); 
	glGetDoublev( GL_PROJECTION_MATRIX, matProjection ); 
	glGetIntegerv( GL_VIEWPORT, viewport ); 
	double winX = (double)mousePos.x(); 
	double winY = viewport[3] - (double)mousePos.y(); 
	gluUnProject(winX, winY, 0.0, matModelView, matProjection, 
		viewport, &startX, &startY, &startZ); 
	gluUnProject(winX, winY, 1.0, matModelView, matProjection, 
		viewport, &endX, &endY, &endZ);

	Vec3 start(startX, startY, startZ), end(endX, endY, endZ);
	if(pStart)
	{
		*pStart = start;
	}
	if(pEnd)
	{
		*pEnd = end;
	}
	return vecUnitVector(end - start);
}

bool pointOnXYPlane( float zDepth, const Vec3& r1, const Vec3& r2, QPointF& pos )
{
	Vec3 P1(-10, -10, zDepth);
	Vec3 P2( 10, -10, zDepth);
	Vec3 P3( 10,  10, zDepth);

	Vec3 V1 = P2 - P1;
	Vec3 V2 = P3 - P1;
	Vec3 V3 = vecCrossProduct(V1, V2);

	Vec3 vRotRay1 = Vec3 ( vecDotProduct (V1, r1-P1 ), vecDotProduct (V2, r1-P1 ), vecDotProduct (V3, r1-P1 ) );
	Vec3 vRotRay2 = Vec3 ( vecDotProduct (V1, r2-P1 ), vecDotProduct (V2, r2-P1 ), vecDotProduct (V3, r2-P1 ) );

	if (vRotRay1.z == vRotRay2.z) return false;

	float fPercent = vRotRay1.z / (vRotRay2.z-vRotRay1.z);
	Vec3 vIntersect2d = vRotRay1 + (vRotRay1-vRotRay2) * fPercent;
	float fX = vIntersect2d.x;
	float fY = vIntersect2d.y;

	pos = QPointF(fX, fY);

	return true;
}
